/** @odoo-module **/
const {
    markup,
    Component,
    onWillStart,
    useEnv,
    useSubEnv,
    useChildSubEnv,
    useRef,
    useState,
    mount,
    xml,
    whenReady,
    onMounted,
    onError,
    loadFile,
    onWillUpdateProps,
    useEffect,
    useComponent
} = owl;
import init_grid_options from '../ag_grid/gridOptions.js';
import numberCellEditor from '../ag_grid/numberCellEditor.js';
import selectMaterialCellEditor from '../ag_grid/selectMaterialCellEditor.js';

class GroupRowInnerRenderer {
    // 初始化
    init(params){
        // console.log(params)
        const eGui = document.createElement('div');
        let _this = this;
        let _html = '';
        let dinner_type_id = params.value;
        dinner_type_id = formatId(dinner_type_id);
        this.owl = params.context.owl_widget;

        let childs = params.node.allLeafChildren.map(v=>v.data);
        let { result,tips } = _this.owl.checkDinnerGroupStockOut(childs);

        eGui.className = 'd-flex align-items-center gap-3';
        _html += `<div class="">${params.valueFormatted}</div>`;
        _html += `<div class="btn-group">`;
        if(result){
            _html += `<button type="button" class="btn btn-outline-primary btn-xs" style="line-height: 1.2">出库</button>`;
        }else{
            _html += `<button type="button" class="btn btn-outline-primary btn-xs" disabled style="line-height: 1.2">出库</button>`;
        }
        _html += `</div>`;
        if(!result){
            _html += `<div class="text-danger">${tips}</div>`;
        }
        eGui.innerHTML = _html;

        eGui.querySelectorAll('button').forEach(function (e){
            e.addEventListener('click',function (ev){
                ev.stopPropagation();
                _this.owl.stockOut(dinner_type_id);
            })
        });
        // 发到this
        this.eGui = eGui
    }
    // 插入页面
    getGui() {
        // console.log('GroupRowInnerRenderer');
        return this.eGui;
    }
    // 刷新
    refresh(params) {
        return false;
    }
}

import {
    arrayRemoveRepeat,
    keepTwoDecimal,
    toObj,
    formatId,
    formatPrice,
    formatDate,
    fullScreen,
    fullExit,
    onFullscreenChange,
    add_site_stock_record_id
} from "../ag_grid/tool.js";


class Record extends Component {
    static template = xml`
    <div style="display: -webkit-flex;display: flex;-webkit-flex-direction: column;flex-direction: column;overflow-y: auto;height: 100%">
    <div class="table-top clearfix">
    <div class="d-flex align-items-center gap-2">
                    <div class="dropdown">
                          <button class="btn dropdown-toggle btn btn-outline-primary btn-xs" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            显示设置
                          </button>
                          <ul class="dropdown-menu">
                            <li  t-foreach="tableForm" t-as="v" t-key="v_index" style="padding-left: 10px;padding-right: 10px;">
                                <div class="form-check" style="margin-bottom: 0;min-height: auto;">
                                    <input class="form-check-input" type="checkbox" t-model="state.tableConfig[v.key]" t-on-change="setVisible" t-att-data-name="v.key"/>
                                    <label class="form-check-label">
                                        <t t-esc="v.name_cn || v.name"/>
                                    </label>
                                </div>
                            </li>
                          </ul>
                    </div>
                    <div class="dropdown">
                          <button class="btn dropdown-toggle btn btn-outline-primary btn-xs" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            筛选
                          </button>
                          <ul class="dropdown-menu">
                            <li  t-foreach="filterForm" t-as="v" t-key="v_index" style="padding-left: 10px;padding-right: 10px;">
                                <div class="form-check" style="margin-bottom: 0;min-height: auto;">
                                    <input class="form-check-input" type="checkbox" t-model="state.filterValue[v.key]" t-on-change="setFilterModel" t-att-data-name="v.key"/>
                                    <label class="form-check-label">
                                        <t t-esc="v.name"/>
                                    </label>
                                </div>
                            </li>
                          </ul>
                    </div>                  
                    <div class="dropdown">
                          <button class="btn dropdown-toggle btn btn-outline-success btn-xs" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            批量增加行
                          </button>
                          <ul class="dropdown-menu">
                            <t t-foreach="dinnerTypeCategoryList" t-as="v" t-key="v_index">
                                <li class="dropdown-item" t-on-click="handle_batch_add" t-att-data-key="v.key">
                                    领料食材（<t t-esc="v.name"/>）
                                </li>
                            </t>
                          </ul>
                    </div>
                    <div class="dropdown">
                          <button class="btn dropdown-toggle btn btn-outline-danger btn-xs" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            批量删除行
                          </button>
                          <ul class="dropdown-menu">
                            <li class="dropdown-item" t-on-click="handle_batch_remove" data-key="nodata">
                                没有数据的食材行
                            </li>
                            <t t-foreach="dinnerTypeCategoryList" t-as="v" t-key="v_index">
                                <li class="dropdown-item" t-on-click="handle_batch_remove" t-att-data-key="v.key">
                                    <t t-esc="v.name"/>
                                </li>
                            </t>
                            
                          </ul>
                    </div>
                    <div t-if="state.isFirstData">当前为初始化数据，保存之后将自动删除未填写的食材行。</div>
                    <div><t t-esc="state.msg"/></div>
<!--                    <div>-->
<!--                            <span t-on-click.stop="toggleInfo" class="info-icon" id="infoTip" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="说明">-->
<!--                                <img src="gmm/static/src/owl/action_client/site_stock_record/images/icon-info.svg" class="d-block"/>-->
<!--                            </span>-->
<!--                        </div>-->
    </div>
    </div>
    <div class="table-top clearfix" t-att-class="state.infoShow">
                <div class="float-start">
                    <div class="form-check-inline">注：</div>
                    <div class="form-check-inline">
                        <span class="bg_gray" style="margin-right: 5px;">浅灰色背景</span>
                        <span>[ 自动计算/不可编辑 ]</span>
                    </div>
                    <div class="form-check-inline">
                        <span class="text-danger" style="margin-right: 5px;">红色字</span>
                        <span>[ 违反规则 ]</span>
                    </div>
                    <div class="form-check-inline">
                        <span class="cell-error" style="margin-right: 5px;"> <span style="position: relative;">红色背景</span></span>
                        <span>[ 违反规则 ]</span>
                    </div>
                    <div class="form-check-inline">
                        <span class="bg_green" style="margin-right: 5px;"> <span style="position: relative;">绿色背景</span></span>
                        <span>[ 特色菜 ]</span>
                    </div>

                    <div class="form-check-inline" t-if="state.tableConfig.color">
                        <span class="text-red-underline" style="margin-right: 5px;">红色下划线</span>
                        <span>[ 价格超出 ]</span>
                    </div>
                    <div class="form-check-inline" t-if="state.tableConfig.color">
                        <span class="text-success" style="margin-right: 5px;">绿色字</span>
                        <span>[ 鲜品 ]</span>
                    </div>
                    <div class="form-check-inline" t-if="state.tableConfig.color">
                        <span class="text-warning" style="margin-right: 5px;">黄色字</span>
                        <span>[ 冻品、半成品 ]</span>
                    </div>

                </div>
                <div class="float-end">
                    <span class="groupBtn" t-on-click.stop="toggleInfo">隐藏</span>
                </div>
            </div>
            <div style="height: 100%">
                <div t-ref="myGrid" style="flex:1" class="ag-theme-balham myGrid Site_stock_record_myGrid" id="Site_stock_record_myGrid"/>
            </div>
    </div>
    `;
    static props = {
        year_month_day: {type: String}
    };

    setup() {
        this.myGrid_ref = useRef('myGrid');
        this.addRowMaxId = '';//表格最大的id
        this.rowData = [];//表格数据

        this.oldCellData = {};
        this.newCellData = {};

        this.del_site_stock_record_ids = [];
        this.creat_site_stock_record_ids = [];

        this.LevelScore = {};
        // this.ismenu_org_group_category_id = '';
        // this.menuCusIds = [];
        this.year_month_day = '';

        this.isOnRangeSelection = false;//正在选择中
        this.rangeSelectionRowIds = [];

        this.state = useState({
            isFirstData:false,
            isUpdateProps:false,
            infoShow: 'hide',
            filterValue:{},
            sidebarFilter: {},
            sidebarFilterCheckAll: {},
            tableConfig: {
                total:true,
                showZero:false,
                stockQty:true,
                stockOutQty:true,
                out:true,
                qty:true
            },
            msg:''
        })
        onWillStart(async () => await this.LoadData(this.props.year_month_day));
        onWillUpdateProps(async next_props => {
            this.state.isUpdateProps = true;
            await this.LoadData(next_props.year_month_day)
        });
        onMounted(this.RenderAG);
        onWillUpdateProps(nextProps => {
            this.LoadData(nextProps.year_month_day)
        });
        this.env.bus.addEventListener('save_record', ({detail}) => {
            // let {create_vals_list,write_vals_list,unlink_ids} = detail;
            let data = this.save();
            // console.log(data);
            detail.create_vals_list = data.create_vals_list;
            detail.write_vals_list = data.write_vals_list;
            detail.unlink_ids = data.unlink_ids;
        })
        this.env.bus.addEventListener('save_record_ok', ({detail}) => {
            console.log('save_record_ok')
            this.setRecordData();
        })
        this.env.bus.addEventListener('stock_out_ok', ({detail}) => {
            console.log('stock_out_ok')
            this.setRecordData();
        })
        this.handle_batch_add = _.debounce(this.batch_add,300);
        this.handle_batch_remove = _.debounce(this.batch_remove,300);
    }
    // 检查该餐别是否可以出库
    checkDinnerGroupStockOut(data){
        // let flag = true;
        let tips = [];
        data.forEach(v=>{
            let { dinner_type_id,material_id } = v;
            if(!material_id){
                return;
            }
            let stock_qty = this.env.getGlobal().material_stock_qty[material_id].stock_qty;
            let total = 0;
            this.env.getIndex().cus_loc.forEach(cus=>{
                let cus_loc_id = cus.cus_loc_id;
                let qty = v['qty||'+cus_loc_id]||0;
                let out = v['out||'+cus_loc_id]||0;
                total += (qty-out);
            })
            if(total>stock_qty){
                tips.push(this.env.getGlobal().material_item[material_id].mname);
            }
        })

        if(tips.length>0){
            return {
                result:false,
                tips:tips.join('、')+' 计划（未出库）大于库存，不能出库，请检查。'
            }
        }else{
            return {
                result:true
            }
        }
    }

    batch_add(e){
        let key = e.target.dataset.key;
        let dinner_type_id = formatId(key);
        let rowData = [];
        let obj = {};

        this.gridOptions.api.forEachNode(node=>{
            if (node.data) {
                let {
                    material_id
                } = node.data;
                if(!material_id){
                    return;
                }
                if(dinner_type_id == node.data.dinner_type_id){
                    obj[material_id] = true;
                }
            }
        });

        this.env.getIndex().site_material_item.forEach(m=>{
            let material_id = m.id;
            if(obj[material_id]){
                return;
            }
            let main_unit_id = m.main_unit_id;
            this.addRowMaxId++;
            let item = {
                id:this.addRowMaxId,
                dinner_type_id:formatId(dinner_type_id),
                material_id:formatId(material_id),
                unit_id:formatId(main_unit_id),
                material_top_category_id:this.env.getGlobal().material_item[material_id].top_category_id,
                dinner_type_name:this.env.getGlobal().dinner_type_category[dinner_type_id].name
            };
            item.LevelScore = this.getLevelScore(item);
            rowData.push(item);
        })
        this.gridOptions.api.applyTransactionAsync({add: rowData}, (res) => {
            this.state.haveChange = true;
            this.env.setHaveChange(true);
            this.gridOptions.api.redrawRows();
        });
    }
    batch_remove(e){
        let key = e.target.dataset.key;
        let rowData = [];
        if(key == 'nodata'){
            this.gridOptions.api.forEachNode(node=>{
                if (node.data) {
                    let total = this.gridOptions.api.getValue('total', node);
                    if(total === 0){
                        rowData.push(node.data);
                    }
                }
            });
        }else{
            let dinner_type_id = formatId(key);
            this.gridOptions.api.forEachNode(node=>{
                if (node.data) {
                    if(dinner_type_id == node.data.dinner_type_id){
                        rowData.push(node.data);
                    }
                }
            });
        }

        this.removeRows(rowData);
    }
    stockOut(dinner_type_id){
        dinner_type_id = formatId(dinner_type_id);
        // 验证出库
        let rowData = [];
        this.gridOptions.api.forEachNode(node=>{
            if (node.data) {
                let {
                    material_id
                } = node.data;
                if(!material_id){
                    return;
                }
                if(node.data.dinner_type_id == dinner_type_id){
                    rowData.push(node.data);
                }
            }
        });
        let { result } = this.checkDinnerGroupStockOut(rowData);
        if(result){
            this.env.stockOutRecord(dinner_type_id);
        }else{
            console.log('出库验证不通过');
        }
    }
    save(){
        let create_vals_list = [];
        let write_vals_list = [];
        let unlink_ids = [];
        let oldCellData = this.oldCellData;
        let newCellData = this.getNewCellData();
        // console.log(newCellData);
        for(let key in oldCellData){
            if(!newCellData[key]){
                unlink_ids.push(oldCellData[key].id);
            }else if(oldCellData[key].unit_qty != newCellData[key].unit_qty){
                write_vals_list.push({
                    ...oldCellData[key],
                    unit_qty:newCellData[key].unit_qty
                })
            }
        }
        for(let key in newCellData){
            let [dinner_type_id,material_id,unit_id,cus_loc_id] = key.split('||');
            if(!oldCellData[key]){
                create_vals_list.push({
                    id:add_site_stock_record_id(),
                    dinner_type_id:formatId(dinner_type_id),
                    material_id:formatId(material_id),
                    unit_id:formatId(unit_id),
                    cus_loc_id:formatId(cus_loc_id),
                    unit_qty:newCellData[key].unit_qty,
                    stock_out_record_detail_id:0,
                    date:this.year_month_day
                })
            }
        }
        return {
            create_vals_list,write_vals_list,unlink_ids
        }

    }
    getNewCellData(){
        let newCellData = {};

        this.gridOptions.api.forEachNode(node=>{
            if (node.data) {
                let {
                    dinner_type_id,material_id,unit_id
                } = node.data;
                if(!material_id){
                    return;
                }
                let total = this.gridOptions.api.getValue('total', node);
                if(this.state.isFirstData && total === 0){
                    return;
                }
                this.env.getIndex().cus_loc.forEach(cus=>{
                    let cus_loc_id = cus.cus_loc_id;
                    let qty = node.data['qty||'+cus_loc_id]||0;
                    newCellData[`${dinner_type_id}||${material_id}||${unit_id}||${cus_loc_id}`] = {
                        unit_qty:Number(qty)
                    };
                })
            }
        });
        return newCellData;
    }
    LoadData(year_month_day){
        if(this.year_month_day == year_month_day){
            return;
        }
        this.year_month_day = year_month_day;
        this.setTableConfig();
        this.setFilterValue();
        this.setLevelScore();
        this.setRecordData();
    }
    //设置表格基础数据
    setRecordData(){
        this.state.msg = '';
        let site_stock_record = this.env.getIndex().site_stock_record;
        // console.log(site_stock_record);
        let oldCellData = {};
        let rowData = [];
        this.addRowMaxId = 0;
        let haveChange = false;
        let changeMaterialIds = [];
        if(site_stock_record.length == 0){
            this.state.isFirstData = true;
            this.env.getIndex().dinner_type_category.forEach(dn=>{
                let dinner_type_id = dn.id;
                this.env.getIndex().site_material_item.forEach(m=>{
                    let material_id = m.id;
                    let main_unit_id = m.main_unit_id;
                    this.addRowMaxId++;
                    let item = {
                        id:this.addRowMaxId,
                        dinner_type_id:formatId(dinner_type_id),
                        material_id:formatId(material_id),
                        unit_id:formatId(main_unit_id),
                        material_top_category_id:this.env.getGlobal().material_item[material_id].top_category_id,
                        dinner_type_name:this.env.getGlobal().dinner_type_category[dinner_type_id].name
                    };
                    item.LevelScore = this.getLevelScore(item);
                    rowData.push(item);
                })
            })
        }else{
            this.state.isFirstData = false;
            let obj = {};
            site_stock_record.forEach(v=>{
                let { cus_loc_id,date,dinner_type_id,material_id,unit_id,unit_qty } = v;
                !obj[`${dinner_type_id}||${material_id}||${unit_id}`] && (obj[`${dinner_type_id}||${material_id}||${unit_id}`] = {});
                obj[`${dinner_type_id}||${material_id}||${unit_id}`][cus_loc_id] = v;
                oldCellData[`${dinner_type_id}||${material_id}||${unit_id}||${cus_loc_id}`] = v;
            })
            for(let key in obj){
                let [dinner_type_id,material_id,unit_id] = key.split('||');
                let main_unit_id = this.env.getGlobal().material_item[material_id].main_unit_id;
                let ratio = 1;
                if(unit_id != main_unit_id){
                    // 与主单位不一致
                    console.log('与主单位不一致');
                    try{
                        ratio = this.env.getMainUnitBomUnitRatio(material_id,unit_id);
                    }catch (e) {

                    }
                }
                this.addRowMaxId++;
                material_id = formatId(material_id);
                dinner_type_id = formatId(dinner_type_id);
                let item = {
                    id:this.addRowMaxId,
                    dinner_type_id:dinner_type_id,
                    material_id:material_id,
                    unit_id:main_unit_id,
                    material_top_category_id:this.env.getGlobal().material_item[material_id].top_category_id,
                    dinner_type_name:this.env.getGlobal().dinner_type_category[dinner_type_id].name
                };
                item.LevelScore = this.getLevelScore(item);
                for(let cus_loc_id in obj[key]){
                    item[`qty||${cus_loc_id}`] = keepTwoDecimal(obj[key][cus_loc_id].unit_qty/ratio);
                    item[`out||${cus_loc_id}`] = keepTwoDecimal(obj[key][cus_loc_id].stock_out_qty/ratio);
                }
                rowData.push(item);
                if(ratio!==1){
                    haveChange = true;
                    if(!changeMaterialIds.includes(material_id)){
                        changeMaterialIds.push(material_id)
                    }
                }
            }
        }
        if(changeMaterialIds.length > 0){
            let names = changeMaterialIds.map(id=>this.env.getGlobal().material_item[id].mname);
            this.state.msg = '食材主单位发生改变,已帮您转换数值，请注意保存。('+names.join('，')+')';
        }
        this.oldCellData = oldCellData;
        this.state.haveChange = haveChange;
        this.env.setHaveChange(haveChange);
        this.rowData = rowData;
        // console.log(oldCellData);
        // console.log(rowData);
        if (this.gridOptions) {
            this.gridOptions.api.setColumnDefs(this.getColumnDefs());
            this.gridOptions.api.setRowData(this.rowData);
            this.gridOptions.api.redrawRows();
        }
    }

    //设置表格显示设置
    setTableConfig() {
        let {

        } = this.env.getIndex().user_config;

        // this.state.tableConfig.costPrice = is_plan_day_show_dish_cost;
    }
    //设置数据筛选值
    setFilterValue(){
        this.env.getIndex().dinner_type_category.forEach(v=>{
            this.state.filterValue[v.id] = true;
        })
    }
    setFilterModel(){
        // console.log(this.state.filterValue);
        let _this = this;
        let dinner_type_name_arr = [];
        for(let id in _this.state.filterValue){
            if(_this.state.filterValue[id]){
                try {
                    let name = this.env.getGlobal().dinner_type_category[id].name;
                    dinner_type_name_arr.push(name);
                }catch (e) {}
            }
        }
        let filterModel = {
            dinner_type_name:{
                type: 'contains',
                values: dinner_type_name_arr
            },
        };
        this.gridOptions.api.setFilterModel(filterModel);
    }
    //显示筛选
    setVisible(e) {
        // console.log('-----setVisible---------');
        if(e){
            let name = e.target.dataset.name;
            if(name == 'showZero'){
                this.gridOptions.api.redrawRows();
            }else{
                this.gridOptions.api.setColumnDefs(this.getColumnDefs());
            }
        }
    }
    // 排序分值
    setLevelScore() {
        let dinner_type_id = {};
        let material_top_category_id = {};
        this.env.getIndex().dinner_type_category.forEach((v,i)=>{
            dinner_type_id[v.id] = i*1000000000000
        });
        this.env.getIndex().material_top_category.forEach((v,i)=>{
            material_top_category_id[v.id] = (i+1)*10000
        });
        this.LevelScore.dinner_type_id = dinner_type_id;
        this.LevelScore.material_top_category_id = material_top_category_id;
    }
    getLevelScore(v) {
        let score = 0;
        if (this.LevelScore.dinner_type_id[v.dinner_type_id]) {
            score += this.LevelScore.dinner_type_id[v.dinner_type_id]
        }
        if (this.LevelScore.material_top_category_id[v.material_top_category_id]) {
            score += this.LevelScore.material_top_category_id[v.material_top_category_id]
        }
        return score;
    }
    // 单元格改变
    onCellValueChanged(params) {
        // console.log('-----onCellValueChanged----');
        // console.log(params);
        if (params.source == "edit" && params.colDef.field == "material_id") {
            this.onMaterialChanged(params);
        }else{
            this.gridOptions.api.redrawRows();
        }
        this.state.haveChange = true;
        this.env.setHaveChange(true);
        //
    }
    onMaterialChanged(params) {
        // console.log('-----onMaterialChanged----');
        let data = params.node.data;
        let material_id = params.newValue;
        let unit_id = this.env.getGlobal().material_item[material_id].main_unit_id;
        let material_top_category_id = this.env.getGlobal().material_item[material_id].top_category_id;
        data.material_id = material_id;
        data.unit_id = unit_id;
        data.material_top_category_id = material_top_category_id;
        data.LevelScore = this.getLevelScore(data);
        this.gridOptions.api.applyTransactionAsync({update: [data]}, (res) => {
            // this.gridOptions.api.refreshCells({force: true});//刷新表格
            this.gridOptions.api.redrawRows();
        });
    }
    // 右键菜单
    setAGMenus(e) {
        // console.log('-------setAGMenus-------');
        console.log(this.rangeSelectionRowIds);
        let node = e.node || {};
        // if (!e.column) {
        //     return;
        // }
        let _this = this;
        let data = node.data;
        // let colId = e.column.colId;
        let menus = [];
        this.env.getIndex().dinner_type_category.forEach(dn=>{
            menus.push({
                name:`新增一行：${dn.name}`,
                action: () => {
                    _this.addRow({dinner_type_id: dn.id});
                },
            });
        })

        if (node.data) {
            menus.push('separator');
            menus.push({
                name: '删除本行',
                action: () => {
                    _this.removeRow(node.data);
                },
                cssClasses: ['text-danger'],
            })
        }
        if(this.rangeSelectionRowIds.length>1){
            menus.push({
                name: `删除所选的${this.rangeSelectionRowIds.length}行`,
                action: () => {
                    _this.removeRowByIds(this.rangeSelectionRowIds);
                    _this.rangeSelectionRowIds = [];
                },
                cssClasses: ['text-danger'],
            })
        }
        return menus;
    }
    removeRow(data){
        this.removeRows([data]);
    }
    removeRowByIds(ids){
        let removeData = [];
        this.gridOptions.api.forEachNode(node=>{
            if (node.data) {
                if(ids.includes(node.data.id)){
                    removeData.push(node.data);
                }
            }
        });
        this.removeRows(removeData);
    }
    async removeRows(removeData){
        let _this = this;
        // 是否已出库
        let flag = false;
        removeData.forEach(v=>{
            let { dinner_type_id,material_id,unit_id } = v;
            if(!material_id){
                return;
            }
            this.env.getIndex().cus_loc.forEach(cus=>{
                let cus_loc_id = cus.cus_loc_id;
                let out = v['out||'+cus_loc_id]||0;
                out > 0 && (flag = true)
            })
        });
        if(flag){
            _this.env.openToast({
                msg:'所选的行有已出库，删除将同步删除出库，确定继续删除？',
                isCancel: true,
                onConfirm: async () => {
                    _this.gridOptions.api.applyTransactionAsync({remove: removeData}, (res) => {
                        _this.gridOptions.api.redrawRows();
                        _this.state.haveChange = true;
                        _this.env.setHaveChange(true);
                        _this.env.saveRecord();
                    });
                },
                onCancel: async () => {}
            })

        }else{
            this.gridOptions.api.applyTransactionAsync({remove: removeData}, (res) => {
                this.state.haveChange = true;
                this.env.setHaveChange(true);
                this.gridOptions.api.redrawRows();
            });
        }
    }
    addRow(data){
        this.addRowMaxId++;
        let newItem = {
            id: this.addRowMaxId,
            ...data
        };
        newItem.LevelScore = this.getLevelScore(newItem);
        this.gridOptions.api.applyTransactionAsync({add: [newItem]}, (res) => {
            this.state.haveChange = true;
            this.env.setHaveChange(true);
            this.gridOptions.api.redrawRows();
        });
    }
    getColumnDefs(){
        let _this = this;
        let cols = [
            {
                headerName: "餐别",
                field: "dinner_type_id",
                hide: true,
                rowGroup: true,
                comparator: (a,b) => {
                    let getData = (v) =>{
                        let data = this.env.getGlobal().dinner_type_category[v];
                        return data;
                    };
                    let getNum = (v)=>{
                        let num = v == 'dn2'?2:v=='dn3'?3:v=='dn5'?5:v=='dn1'?1:6;
                        return num;
                    };
                    let d1 = getData(a);
                    let d2 = getData(b);
                    let d1Number = getNum(d1.dinner_type);
                    let d2Number = getNum(d2.dinner_type);
                    if(d1Number == d2Number){
                        d1Number = d1.dt_no;
                        d2Number = d2.dt_no;
                    }
                    return d1Number - d2Number;
                },
                valueFormatter: params => {
                    if (params.value && params.value != '') {
                        return _this.env.getGlobal().dinner_type_category[params.value].name;
                    } else {
                        return ''
                    }
                },
            },
            {
                headerName: 'LevelScore',
                field: 'LevelScore',
                hide:true,
                sortable: true,
                // filter: 'agNumberColumnFilter',
            },
            {
                headerName: 'dinner_type_name',
                field: 'dinner_type_name',
                hide:true,
            },
            {
                headerName: "类别",
                field: "material_top_category_id",
                pinned: 'left',
                lockPosition:'left',
                width: 40,
                minWidth:40,
                // maxWidth:40,
                menuTabs: [],
                editable: false,
                rowSpan: params => {
                    return _this.getRowSpan(params,'material_top_category_id');
                },
                cellClassRules: {
                    'row-span':(params)=> _this.getRowSpan(params,'material_top_category_id') !=1,
                },
                valueFormatter: params => {
                    if (params.value && params.value != '') {
                        return _this.env.getGlobal().material_top_category[params.value].name;
                    } else {
                        return ''
                    }
                },
                hide:!_this.isShowColId('material_top_category_id'),
            },
            {
                headerName: "物料",
                field: "material_id",
                menuTabs: [],
                width: 120,
                minWidth:120,
                // maxWidth:120,
                type: 'editableColumn',
                cellEditor: selectMaterialCellEditor,
                cellEditorParams: (params) => {
                    let dn = params.data.dinner_type_id;
                    let mid = params.data.material_id;
                    let material_item = params.context.owl_widget.env.getIndex().material_item;
                    let material_ids = [];
                    _this.gridOptions.api.forEachNode(node=>{
                        if (node.data) {
                            let {
                                dinner_type_id,material_id
                            } = node.data;
                            if(material_id && dn == dinner_type_id && material_id!=mid){
                                material_ids.push(material_id);
                            }
                        }
                    });
                    material_item = material_item.filter(v=>!material_ids.includes(v.id)).map(v=>{
                        return {
                            ...v,
                            name:v.mname
                        }
                    })
                    return {
                        values: material_item
                    };
                },
                suppressPaste:true,
                pinned: 'left',
                lockPosition:'left',
                valueFormatter: params => {
                    if (params.value && params.value != '') {
                        return params.context.owl_widget.env.getGlobal().material_item[params.value].mname;
                    } else {
                        return ''
                    }
                },
                hide:!_this.isShowColId('material_id'),
            },
            {
                headerName: "单位",
                field: "unit_id",
                pinned: 'left',
                lockPosition:'left',
                width: 40,
                minWidth:40,
                maxWidth:40,
                menuTabs: [],
                editable: false,
                valueFormatter: params => {
                    if (params.value && params.value != '') {
                        return _this.env.getGlobal().material_purchase_unit_category[params.value].name;
                    } else {
                        return ''
                    }
                },
                cellClassRules: {
                    'bg_gray': (params) => true
                },
                hide:!_this.isShowColId('unit_id'),
            },
            {
                headerName: "总数",
                field: "total",
                menuTabs: [],
                pinned: 'right',
                lockPosition:'right',
                width: 50,
                minWidth:50,
                maxWidth:50,
                editable: false,
                valueGetter: (params) => {
                    let sum = 0;
                    _this.env.getIndex().cus_loc.forEach(cus=>{
                        let cus_loc_id = cus.cus_loc_id;
                        sum += Number(params.data[`qty||${cus_loc_id}`]) || 0;
                    })
                    return sum;
                },
                hide:!_this.isShowColId('total'),
                cellClassRules: {
                    'bg_gray': (params) => true
                },
            },
            {
                headerName: "库存",
                field: "stockQty",
                menuTabs: [],
                pinned: 'right',
                lockPosition:'right',
                width: 50,
                minWidth:50,
                maxWidth:50,
                editable: false,
                valueGetter: (params) => {
                    let stock_qty = 0;
                    try {
                        stock_qty = this.env.getGlobal().material_stock_qty[params.data.material_id].stock_qty;
                    }catch (e) {}
                    return stock_qty;
                },
                hide:!_this.isShowColId('stockQty'),
                cellClassRules: {
                    'bg_gray': (params) => true
                },
            },
            {
                headerName: "已出库",
                field: "stockOutQty",
                menuTabs: [],
                pinned: 'right',
                lockPosition:'right',
                width: 50,
                minWidth:50,
                maxWidth:50,
                editable: false,
                valueGetter: (params) => {
                    let sum = 0;
                    _this.env.getIndex().cus_loc.forEach(cus=>{
                        let cus_loc_id = cus.cus_loc_id;
                        sum += Number(params.data[`out||${cus_loc_id}`]) || 0;
                    })
                    return sum;
                },
                // valueGetter: (params) => {
                //     let num= 0;
                //     try {
                //         let dinner_type_id = params.data.dinner_type_id;
                //         let material_id = params.data.material_id;
                //         let unit_id = params.data.unit_id;
                //         let stock_out_record_detail_id = 0;
                //         _this.env.getIndex().cus_loc.forEach(cus=>{
                //             let cus_loc_id = cus.cus_loc_id;
                //             if(stock_out_record_detail_id!==0){
                //                 return;
                //             }
                //             if(_this.oldCellData[`${dinner_type_id}||${material_id}||${unit_id}||${cus_loc_id}`]){
                //                 stock_out_record_detail_id = _this.oldCellData[`${dinner_type_id}||${material_id}||${unit_id}||${cus_loc_id}`].stock_out_record_detail_id;
                //             }
                //         })
                //         if(stock_out_record_detail_id){
                //             num = _this.env.getIndex().stock_out_record_detail.find(v=>v.id == stock_out_record_detail_id).main_unit_qty;
                //         }
                //     }catch (e) {
                //     }
                //     return num;
                // },
                hide:!_this.isShowColId('stockOutQty'),
                cellClassRules: {
                    'bg_gray': (params) => true
                },
            },
        ];
        this.env.getIndex().cus_loc.forEach(cus=>{
            let cusCol = {
                headerName: cus.plan_day_cus_name,
                children:[
                    {
                        headerName: '计划',
                        field: 'qty||'+cus.cus_loc_id,
                        width: 50,
                        minWidth:50,
                        maxWidth:50,
                        menuTabs: [],
                        cellEditor:numberCellEditor,
                        cellEditorParams: (params) => {
                            return {
                                values:{
                                    decimal: true,
                                    toFixed:2
                                }

                            };
                        },
                        type: 'editableColumn',
                        suppressPaste:true,
                        hide:!_this.isShowColId('qty||'+cus.cus_loc_id),
                        valueFormatter: params => {
                            if(_this.state.tableConfig.showZero && !params.value){
                                return 0
                            }
                            if(!_this.state.tableConfig.showZero && !params.value){
                                return ''
                            }
                            return params.value
                        },
                    },
                    {
                        headerName: '已出库',
                        field: 'out||'+cus.cus_loc_id,
                        width: 50,
                        minWidth:50,
                        maxWidth:50,
                        menuTabs: [],
                        editable: false,
                        hide:!_this.isShowColId('out||'+cus.cus_loc_id),
                        valueFormatter: params => {
                            if(_this.state.tableConfig.showZero && !params.value){
                                return 0
                            }
                            if(!_this.state.tableConfig.showZero && !params.value){
                                return ''
                            }
                            return params.value
                        },
                        cellClassRules: {
                            'bg_gray': (params) => true
                        },
                    }
                ]


            };
            cols.push(cusCol)
        });
        return cols
    }
    // 单元格是否可编辑
    isCellEditable(params) {
        let flag = true;
        let data = params.data;
        let colId = params.colDef.field;
        return flag;
    }
    isShowColId(colId) {
        // let menuCusIds = this.menuCusIds;
        let alwaysShowColIds = ['material_id', 'unit_id','material_top_category_id'];
        let flag = false;
        if (alwaysShowColIds.includes(colId)) {
            flag = true;
            return flag;
        }
        if (colId.startsWith('qty||')) {
            flag = this.state.tableConfig['qty'];
            // let [pre, cusId] = colId.split('_');
            // if (menuCusIds.includes(Number(cusId))) {
            //     // 有菜单
            //     flag = this.state.tableConfig.menu;
            // } else {
            //     flag = this.state.tableConfig.nomenu;
            // }
            return flag;
        }
        if (colId.startsWith('out||')) {
            flag = this.state.tableConfig['out'];
            return flag;
        }
        if (['total','stockQty','stockOutQty'].includes(colId)) {
            flag = this.state.tableConfig[colId];
            return flag;
        }
        return flag;
    }
    // 类别跨行数
    getRowSpan(params,colId){
        let span = 0;
        let data = params.data;
        let value = data[colId];
        let nodes = [];
        let flag = true;
        let rowIndex = ''
        params.api.forEachNode((v)=>{
            nodes.push(v)
            if(v.data && v.data.id == data.id){
                rowIndex = v.rowIndex
            }
        });
        nodes.sort((a,b)=>{return a.rowIndex-b.rowIndex});
        if(rowIndex && nodes[rowIndex-1] && nodes[rowIndex-1].data && nodes[rowIndex-1].data[colId] == value){
            return 1;
        }
        nodes.forEach((v,i)=>{
            if(!flag){
                return;
            }
            if (v.data == undefined){
                return;
            }
            if(v.data[colId] == value && v.rowIndex>=rowIndex){
                span++;
                if(!nodes[i+1] || !nodes[i+1].data || nodes[i+1].data[colId] != value){
                    flag = false;
                }
            }
        });
        return span;
    }
    SetAGOptions() {
        let _this = this;
        console.log('-----SetAGOptions----');
        let columnDefs = this.getColumnDefs();

        this.gridOptions = Object.assign({}, init_grid_options(), {
            tooltipShowDelay: 500,
            columnDefs: columnDefs,
            suppressRowHoverHighlight:false,
            columnHoverHighlight: true,
            groupHeaderHeight: 30,
            headerHeight: 30,
            rowData: this.rowData,
            context: {
                owl_widget: _this
            },
            groupRowRendererParams: {
                suppressCount: true,
                innerRenderer: GroupRowInnerRenderer,
                editable: false
            },
            valueCache: 1,
            onCellEditingStarted:async (event)=>{
                if(!_this.env.LoadSecDataFlag()){
                    // console.log('onCellEditingStarted');
                    await _this.env.LoadSecData()
                }
            },
            onCellValueChanged: (e) => {
                // console.log(e);
                _this.onCellValueChanged(e);
            },
            getContextMenuItems: (e) => {
                return _this.setAGMenus(e);
            },
            getRowId: (params) => {
                return params.data.id;
            },
            onGridReady: function (params) {
                let defaultSortModel = [
                    { colId: 'dinner_type_id', sort: 'asc', sortIndex: 0 },
                    {colId: 'LevelScore', sort: 'asc', sortIndex: 1},
                ];
                params.columnApi.applyColumnState({state: defaultSortModel});
            },
            columnTypes: {
                editableColumn: {
                    editable: (params) => {
                        return _this.isCellEditable(params);
                    },
                }
            },
            getRowStyle: params => {
                if (params && params.node && params.node.data) {
                    let data = params.node.data;
                    // return {background: '#f4f6fa'};
                }
            },
            getRowClass: params => {
                let classArr = [];
                if (params && params.node && params.node.data && _this.getRowSpan(params, 'material_top_category_id') > 1) {
                    classArr.push('RowSpanFirst');
                }
                return classArr.join('  ');
            },
            stopEditingWhenCellsLoseFocus:true,

            // processDataFromClipboard: _this.processDataFromClipboard.bind(_this),
            // groupRowRendererParams: {
            //     suppressCount: true,
            //     innerRenderer: GroupRowInnerRenderer,
            //     editable: false
            // },
            onCellClicked: (params) => {
                // return _this.onCellClicked(params);
            },
            onRangeSelectionChanged: (event) => {
                return _this.onRangeSelectionChanged(event);
            },

            cellFlashDelay: 1000,
            cellFadeDelay: 500,
        })
    }
    RenderAG() {
        let _this = this;
        this.SetAGOptions();
        this.agGrid = new agGrid.Grid(this.myGrid_ref.el, this.gridOptions);
        // new bootstrap.Tooltip('#infoTip');
    }

    onRangeSelectionChanged(event) {
        let cellRanges = this.gridOptions.api.getCellRanges();
        // if no selection, clear all the results and do nothing more
        if (!cellRanges || cellRanges.length === 0) {
            return;
        }
        let api = this.gridOptions.api;
        let rangeSelectionRowIds = {};
        let cellNum = 0;
        if (cellRanges) {
            cellRanges.forEach(function (range) {
                // get starting and ending row, remember rowEnd could be before rowStart
                let startRow = Math.min(range.startRow.rowIndex, range.endRow.rowIndex);
                let endRow = Math.max(range.startRow.rowIndex, range.endRow.rowIndex);
                for (let rowIndex = startRow; rowIndex <= endRow; rowIndex++) {
                    range.columns.forEach(function (column) {
                        let rowModel = api.getModel();
                        let rowNode = rowModel.getRow(rowIndex);
                        if(rowNode.data && rowNode.data.id){
                            rangeSelectionRowIds[rowNode.data.id] = true;
                        }
                    });
                }
            });
        }
        if (event.started) {
            this.isOnRangeSelection = true;
        }
        if (event.finished) {
            this.isOnRangeSelection = false;
            this.rangeSelectionRowIds = Object.keys(rangeSelectionRowIds).map(v => Number(v));
        }
    }

    get tableForm(){
        let arr = [
            {name: '总数', key: 'total'},
            {name: '库存', key: 'stockQty'},
            {name: '已出库', key: 'stockOutQty'},
            {name: '显示0', key: 'showZero'},
            {name: '客户计划', key: 'qty'},
            {name: '客户已出库', key: 'out'},
            // {name: '有菜单', key: 'menu'},
            // {name: '无菜单', key: 'nomenu'},
        ];

        return arr
    };
    get filterForm(){
        let arr = this.env.getIndex().dinner_type_category.map(v=>{
            return {
                name:v.name,
                key: v.id
            }
        });
        return arr
    }
    get dinnerTypeCategoryList(){
        let arr = this.env.getIndex().dinner_type_category.map(v=>{
            return {
                name:v.name,
                key: v.id
            }
        });
        return arr
    }
    // 展开/关闭
    toggleInfo() {
        this.state.infoShow = this.state.infoShow == 'hide' ? 'show' : 'hide';
    }
}

export {
    Record
}
